<?php
class Anchor_redis extends Common_redis_model{
	public function __construct(array $params = array()) 
	{
		parent::__construct();
		$this->params=$params;
	}
	
	function delete_live_cache( $anchor_id = '',$type = 1){
		if(stripos($this->params['channel'],':list')===false){
			$this->params['channel'] .= ':list';	
		}
		$keys = $this->redis->keys($this->params['channel'].":anchor:". $anchor_id);
		if($keys){
			$this->redis->del($keys);
		}
		
	}
	function set_live_cache($data = array()) {
		if(stripos($this->params['channel'],':list')===false){
			$this->params['channel'] .= ':list';	
		}
		$key = $this->params['channel'].":anchor:" . $data['anchor_id'];
		$this->redis->hmset($key ,$data);//设置redis key
		
		
		$redis_live_key = $this->params['channel'].":list:".$data['type'];
		$this->redis->zAdd( $redis_live_key , $data['popularity'],$data['anchor_id']);
		$redis_live_key = $this->params['channel'].":list";
		$this->redis->zAdd( $redis_live_key , $data['popularity'],$data['anchor_id']);
	}
	
	function get_anchor_cache( $redis_anchor_key = '' ) {
		$redis_anchor_item = $this->redis->hgetall($redis_anchor_key);
		return $redis_anchor_item;
	}
	function set_anchor_val_cache( $redis_anchor_key ,$key = '', $val = '' ) {
		$this->redis->hset( $redis_anchor_key ,$key, $val);
	}

	function get_anchor_val_cache( $redis_anchor_key ,$key = '') {
		return $this->redis->hget( $redis_anchor_key ,$key);
	}
	
	function get_live_list($where = array(),$limit = 0, $offset = 10) {
		if(stripos($this->params['channel'],':list')===false){
			$this->params['channel'] .= ':list';	
		}
		$lists = $score = array();
		$redis_live_key = $this->params['channel'].":".$where['type'];
		
		$star 	= !empty($limit)? $limit * $offset : $limit;
		$end	= !empty($offset) ? $offset * ($limit +1)  : $offset;
		$count = (int) $this->redis->zSize($redis_live_key);
		if( !empty($count)) {
			$lists['result'] = array();
			$score	= $this->redis->zRevRange($redis_live_key, $star, ($end-1), FALSE);
			if(!empty($score)) {
				foreach($score as $key=>$val) {
					$lists['result'][] = $this->get_anchor_cache($this->params['channel'].":anchor:" . $val);
				}
				
			}
			$lists['count'] 	= !empty($count) ? (int)$count : 0;
		}
		return $lists;
	}

	function get_all_live_list() {
		if(stripos($this->params['channel'],':list')===false){
			$this->params['channel'] .= ':list';	
		}
		$redis_live_key = $this->params['channel'].":list";
		$score	= $this->redis->zRevRange($redis_live_key, 0,-1, FALSE);
		return $score;
	}
	
	//根据直播id得到 推送地址
	function get_push_url ($anchor_id = 0,$cdn = 0) {
		if(stripos($this->params['channel'],':list')===false){
			$this->params['channel'] .= ':list';	
		}
		$redis_anchor_key = $this->params['channel'].':anchor:'.$anchor_id;
		$redis_anchor_item = $this->get_anchor_cache( $redis_anchor_key );
		$return = $redis_anchor_item;
		//唯一stream_id
		if(empty($return['stream_id'])) {
			$return['stream_id'] = $this->get_stream_id($anchor_id);
		}
		//用户已经开启房间，重新用之前的cdn
		$user_anchor = get_field_by_where("user", "is_live,cdn", " id = ".$anchor_id);
		if(!empty($user_anchor['is_live'])) {
			$cdn = $user_anchor['cdn'];
			$user_anchor_cdn = get_field_by_where("user_anchor_cdn", "id,cdn", "id = " .$cdn);
		}else {
			if(!empty($cdn)){//如果传了cdn参数优先
				$user_anchor_cdn = get_field_by_where("user_anchor_cdn", "id,cdn", "status = 1 AND id=$cdn");
			}
			if(empty($user_anchor_cdn)){//没有有效的指定cdn则随机取一个
				$user_anchor_cdn = get_field_by_where("user_anchor_cdn", "id,cdn", "status = 1 ORDER BY rand()");	
			}
			if(!empty($user_anchor_cdn['id'])) {
				$cdn = $user_anchor_cdn['id'];
			}
		}
		//判断如果不是七牛自己生成流ID
		if($cdn !=1){
			if(strpos($return['stream_id'],'.') !== false){
				$return['stream_id'] = $this->get_stream_id($anchor_id,true);
			}
		}else{
			if(strpos($return['stream_id'],'.') === false){
				$return['stream_id'] = $this->get_stream_id($anchor_id,true);
			}
		}
		//获取七牛推送地址
		if($cdn == 1) {
			if(empty($return['qiniu_publish_url'])) {
				try {
					$stream = $this->qiniu_stream($return['stream_id']);
					$return['qiniu_publish_url'] = $stream->rtmpPublishUrl();
					$this->set_anchor_val_cache( $redis_anchor_key ,'qiniu_publish_url', $return['qiniu_publish_url'] );
				} catch (Exception $e) {
					
				}
			}
			$return['publish_url'] = !empty($return['qiniu_publish_url']) ? $return['qiniu_publish_url'] : '';
		}else if ($cdn == 2) {//帝联
			if(empty($return['dnion_publish_url'])) {
				try {
					$url = 'http://122.11.50.108:90/blackname?app=ysxgzd&type=black&'.$return['stream_id'];
					$ch = curl_init();
					curl_setopt($ch, CURLOPT_URL, $url);
					//设置curl_exec返回的值包含Http头
					curl_setopt($ch, CURLOPT_HEADER, 0);
					//设置curl_exec返回的值包含Http内容
					curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);       
					//设置抓取跳转（http 301，302）后的页面
					curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
					//设置最多的HTTP重定向的数量
					curl_setopt($ch, CURLOPT_MAXREDIRS, 2);

					//服务器返回的数据
					$data = curl_exec($ch);
					if(!empty($data)) {
						$data = json_decode($data,TRUE);
						if(!empty($data)) {
							foreach($data['content']['all']['blackname'] as $key=>$val) {
								if($val == $return['stream_id']) {
									$return['dnion_publish_url'] = 'rtmp://ysxup.dnion.com/ysxgzd/'.$return['stream_id'];
									$this->set_anchor_val_cache( $redis_anchor_key ,'dnion_publish_url', $return['dnion_publish_url'] );
								}
							}
						}
					}
				} catch (Exception $e) {
					
				}
			}
			
			$return['publish_url'] = !empty($return['dnion_publish_url']) ? $return['dnion_publish_url'] : '';
		}else if ($cdn == 3) {
			if(empty($return['cc_publish_url'])) {
				try{
					$return['cc_publish_url'] = 'rtmp://publishcc.youshixiu.com/live/'.$return['stream_id'];
					$this->set_anchor_val_cache( $redis_anchor_key ,'cc_publish_url', $return['cc_publish_url'] );
				}catch (Exception $e) {
					
				}
			}
			$return['publish_url'] = !empty($return['cc_publish_url']) ? $return['cc_publish_url'] : '';
		}else if ($cdn == 4) {
			// if(empty($return['ws_publish_url'])) {
				try{
					$CI =& get_instance();
					$CI->config->load('ws_config');
        			$ws_config  = $CI->config->item('ws_url_config');
					$return['ws_publish_url'] = $ws_config['pre_ws_publish_url'].$return['stream_id'];
					$this->set_anchor_val_cache( $redis_anchor_key ,'ws_publish_url', $return['ws_publish_url'] );
				}catch (Exception $e) {
					
				}
			// }
			$return['publish_url'] = !empty($return['ws_publish_url']) ? $return['ws_publish_url'] : '';
		}else if ($cdn == 5) {
			$aliyun_publish_url_redis_key=$this->params['channel'].":publish_url:aliyun_publish_url:".$anchor_id;
			if(empty($return['aliyun_publish_url']) || !$this->redis->exists($aliyun_publish_url_redis_key)) {
				try{
					$CI =& get_instance();
					$this->CI->config->load('aliyun_config');
					$aliyun_config = $this->CI->config->item('aliyun');
					//$return['stream_id']='test888';
					$Timestamp=time()+(3600*24);
					//$Timestamp=1481505257;
					$Rand=0;
					$Uid=0;
					$Key=$aliyun_config['auth_key'];
					$md5hash=md5('/'.$aliyun_config['app_name'].'/'.$return['stream_id'].'-'.$Timestamp.'-'.$Rand.'-'.$Uid.'-'.$Key);
					$auth_key=$Timestamp.'-'.$Rand.'-'.$Uid.'-'.$md5hash;
					//$return['aliyun_publish_url'] = $aliyun_config['pre_aliyun_publish_url'].$aliyun_config['app_name'].'/'.$return['stream_id'].'?vhost='.$aliyun_config['vhost'].'&auth_key='.$auth_key;
					if($Key){
						$return['aliyun_publish_url'] = $aliyun_config['pre_aliyun_publish_url'].$aliyun_config['app_name'].'/'.$return['stream_id'].'?auth_key='.$auth_key;
					}else{
						$return['aliyun_publish_url'] = $aliyun_config['pre_aliyun_publish_url'].$aliyun_config['app_name'].'/'.$return['stream_id'];
					}
					$this->set_anchor_val_cache( $redis_anchor_key ,'aliyun_publish_url', $return['aliyun_publish_url'] );
					$this->redis->setex($aliyun_publish_url_redis_key,(23*3600),1);
				}catch (Exception $e) {
					
				}
			}
			$return['publish_url'] = !empty($return['aliyun_publish_url']) ? $return['aliyun_publish_url'] : '';
		}
		
		$result = array();
		$result['publish_url'] 			= !empty($return['publish_url']) ? $return['publish_url'] : '';
		$result['test_publish_url'] 	= !empty($return['publish_url']) ? $return['publish_url'] : '';
		$result['cdn'] 					= $cdn;
		return $result;
	}
	//根据直播id得到 播放地址
	function get_live_video_url($anchor_id = 0,$cdn = 1) {
		if(stripos($this->params['channel'],':list')===false){
			$this->params['channel'] .= ':list';	
		}
		$redis_anchor_key = $this->params['channel'].':anchor:'.$anchor_id;
		$redis_anchor_item = $this->get_anchor_cache( $redis_anchor_key );
		$return = $redis_anchor_item;
		//唯一stream_id
		if(empty($return['stream_id'])) {
			$return['stream_id'] = $this->get_stream_id($anchor_id);
		}
		if($cdn == 1) {
			if(empty($return['qiniu_rtmp_video_url']) || empty($return['qiniu_hls_video_url'])) {
				$stream = $this->qiniu_stream($return['stream_id']);
				$rtmp_live_url = $stream->rtmpLiveUrls();
				$return['qiniu_rtmp_video_url'] = !empty($rtmp_live_url['ORIGIN']) ? $rtmp_live_url['ORIGIN'] : '';
				$hls_live_url = $stream->hlsLiveUrls();
				$return['qiniu_hls_video_url'] = !empty($hls_live_url['ORIGIN']) ? $hls_live_url['ORIGIN'] : '';
				$this->set_anchor_val_cache( $redis_anchor_key ,'qiniu_rtmp_video_url', $return['qiniu_rtmp_video_url'] );
				$this->set_anchor_val_cache( $redis_anchor_key ,'qiniu_hls_video_url', $return['qiniu_hls_video_url'] );
			}
			$return['rtmp_video_url'] 	= $return['qiniu_rtmp_video_url'];
			$return['hls_video_url'] 	= $return['qiniu_hls_video_url'];
		}else if ($cdn == 2) {
			if(empty($return['dnion_rtmp_video_url']) || empty($return['dnion_hls_video_url'])) {
				$return['dnion_rtmp_video_url'] = 'rtmp://ysxdown.dnion.com/ysxgzd/'. $return['stream_id'];
				$return['dnion_hls_video_url'] = 'http://ysxhlsdown.dnion.com/ysxgzd/'. $return['stream_id'] .'/index.m3u8';
				$this->set_anchor_val_cache( $redis_anchor_key ,'dnion_rtmp_video_url', $return['dnion_rtmp_video_url'] );
				$this->set_anchor_val_cache( $redis_anchor_key ,'dnion_hls_video_url', $return['dnion_hls_video_url'] );
			}
			$return['rtmp_video_url'] 	= $return['dnion_rtmp_video_url'];
			$return['hls_video_url'] 	= $return['dnion_hls_video_url'];
		}else if ($cdn == 3) {
			if(empty($return['cc_rtmp_video_url']) || empty($return['cc_hls_video_url'])) {
				$return['cc_rtmp_video_url'] = 'rtmp://live-rtmpcc.youshixiu.com/live/'. $return['stream_id'];
				$return['cc_hls_video_url'] = 'http://live-hlscc.youshixiu.com/live/'. $return['stream_id'] .'/index.m3u8';
				$this->set_anchor_val_cache( $redis_anchor_key ,'cc_rtmp_video_url', $return['cc_rtmp_video_url'] );
				$this->set_anchor_val_cache( $redis_anchor_key ,'cc_hls_video_url', $return['cc_hls_video_url'] );
			}
			$return['rtmp_video_url'] 	= $return['cc_rtmp_video_url'];
			$return['hls_video_url'] 	= $return['cc_hls_video_url'];
		}else if ($cdn == 4) {
			$CI =& get_instance();
			$CI->config->load('ws_config');
        	$ws_config  = $CI->config->item('ws_url_config');
			// if(empty($return['ws_rtmp_video_url']) || empty($return['ws_hls_video_url'])) {
				$return['ws_flv_video_url'] = $ws_config['pre_ws_flv_video_url']. $return['stream_id'].'.flv';
				$return['ws_rtmp_video_url'] = $ws_config['pre_ws_rtmp_video_url']. $return['stream_id'];
				$return['ws_hls_video_url'] = $ws_config['pre_ws_hls_video_url']. $return['stream_id'] .'.m3u8';
				$this->set_anchor_val_cache( $redis_anchor_key ,'ws_rtmp_video_url', $return['ws_rtmp_video_url'] );
				$this->set_anchor_val_cache( $redis_anchor_key ,'ws_hls_video_url', $return['ws_hls_video_url'] );
			// }
			$return['rtmp_video_url'] 	= $return['ws_rtmp_video_url'];
			$return['flv_video_url'] 	= $return['ws_flv_video_url'];
			$return['hls_video_url'] 	= $return['ws_hls_video_url'];
		}else if ($cdn == 5) {
			$CI =& get_instance();
			$this->CI->config->load('aliyun_config');
			$aliyun_config = $this->CI->config->item('aliyun');
			$Key=$aliyun_config['auth_key'];
			$aliyun_rtmp_video_url_redis_key=$this->params['channel'].":video_url:aliyun_rtmp_video_url:".$anchor_id;
			$update_cache=false;
			if(strpos($return['aliyun_rtmp_video_url'],'.') !== false){
				$update_cache=true;
			}
			if(empty($return['aliyun_rtmp_video_url']) || !$this->redis->exists($aliyun_rtmp_video_url_redis_key) || $update_cache) {
				$Timestamp=time()+(3600*24*365);
				$Rand=0;
				$Uid=0;
				//$Timestamp='1477905557';
				//$return['stream_id']='test888';
				if($Key){
					$md5hash=md5('/'.$aliyun_config['app_name'].'/'.$return['stream_id'].'.flv-'.$Timestamp.'-'.$Rand.'-'.$Uid.'-'.$Key);
					$auth_key=$Timestamp.'-'.$Rand.'-'.$Uid.'-'.$md5hash;
					$return['aliyun_flv_video_url'] = $aliyun_config['pre_aliyun_flv_video_url']. $aliyun_config['app_name'].'/'.$return['stream_id'].'.flv?auth_key='.$auth_key;
					$md5hash=md5('/'.$aliyun_config['app_name'].'/'.$return['stream_id'].'-'.$Timestamp.'-'.$Rand.'-'.$Uid.'-'.$Key);
					$auth_key=$Timestamp.'-'.$Rand.'-'.$Uid.'-'.$md5hash;
					$return['aliyun_rtmp_video_url'] = $aliyun_config['pre_aliyun_rtmp_video_url'].$aliyun_config['app_name'].'/'. $return['stream_id'].'?auth_key='.$auth_key;
					$md5hash=md5('/'.$aliyun_config['app_name'].'/'.$return['stream_id'].'.m3u8-'.$Timestamp.'-'.$Rand.'-'.$Uid.'-'.$Key);
					$auth_key=$Timestamp.'-'.$Rand.'-'.$Uid.'-'.$md5hash;
					$return['aliyun_hls_video_url'] = $aliyun_config['pre_aliyun_hls_video_url'].$aliyun_config['app_name'].'/'. $return['stream_id'].'.m3u8?auth_key='.$auth_key;
				}else{
					$return['aliyun_flv_video_url'] = $aliyun_config['pre_aliyun_flv_video_url']. $aliyun_config['app_name'].'/'.$return['stream_id'].'.flv';
					$return['aliyun_rtmp_video_url'] = $aliyun_config['pre_aliyun_rtmp_video_url'].$aliyun_config['app_name'].'/'. $return['stream_id'];
					$return['aliyun_hls_video_url'] = $aliyun_config['pre_aliyun_hls_video_url'].$aliyun_config['app_name'].'/'. $return['stream_id'].'.m3u8';
				}
				$this->set_anchor_val_cache( $redis_anchor_key ,'aliyun_rtmp_video_url', $return['aliyun_rtmp_video_url'] );
				$this->set_anchor_val_cache( $redis_anchor_key ,'aliyun_flv_video_url', $return['aliyun_flv_video_url'] );
				$this->set_anchor_val_cache( $redis_anchor_key ,'aliyun_hls_video_url', $return['aliyun_hls_video_url'] );
				$this->redis->setex($aliyun_rtmp_video_url_redis_key,(24*3600*364),1);
			}
			$return['rtmp_video_url'] 	= $return['aliyun_rtmp_video_url'];
			$return['flv_video_url'] 	= $return['aliyun_flv_video_url'];
			$return['hls_video_url'] 	= $return['aliyun_hls_video_url'];
		}
		return $return;
	}
	
	//开始直播统一处理
	function start_live($anchor_id = 0,$cdn = 1) {
		
		//$cdn = 4;//由于安卓cdn缓存的原因，这里临时强制所有的回去观看CDN走4 即网宿的CDN add by qzg 20160707
		/*$this->CI->db->where('id', (int)$anchor_id);
		$this->CI->db->update('user', array('cdn'=> $cdn));*/
		
		$sql = "SELECT u.id AS uid,u.house_password,u.type_id,u.xmpp_password,u.is_reg_xmpp,u.nick,u.signature,u.head_image_url,u.sex,u.verified_anchor,u.title,u.description,u.orientation,u.province,u.city,u.stream_id,u.start_time,u.image_url,u.cdn,u.continue_time,u.is_live,u.is_push,u.f_count,u.up_count,u.h_count_base,u.cate_id,u.status FROM {$this->CI->db->dbprefix}user AS u WHERE u.id = ".$anchor_id;
		$anchor_info = $this->CI->db->query($sql)->row_array();
		if(empty($anchor_info['stream_id'])) {//未存在主播
			$result = array('result_code' => 10033);
		}else {
			$data = array();
			// $data['disconnect_time'] = 0;//清除断线状态
			$data['disconnect_time'] = time();//清除断线状态
			$data['is_live'] = 1;
			// $data['is_push'] = 1;
			$data['cdn'] = $cdn;
		//	$data['cate_id'] = $cate_id;

			/* end */
			if(empty($anchor_info['start_time'])) {//开始直播
				$data['start_time'] = time(); //开始直播设置开始时间为当前时间
			}

			$CI =& get_instance();
			$CI->config->load('qiniu_config');
			$qiniu_config = $CI->config->item('THINK_SDK_QINIU');
			//缩略图地址
			$data['realtime_image_url']='';
			if($anchor_info['cdn'] == 1){
				$data['realtime_image_url'] = 'http://pili-static.'.$qiniu_config['HUB_DOMAIN'].'/'.$qiniu_config['HUB'].'/' . $anchor_info['stream_id'] . '.jpg';
			}elseif($anchor_info['cdn'] == 2){
				$data['realtime_image_url'] = 'http://ysxjt.dnion.com/ysxgzd/'. $anchor_info['stream_id'].'.jpg';
			}elseif($anchor_info['cdn'] == 5){
				$this->CI->config->load('aliyun_config');
				$aliyun_config = $this->CI->config->item('aliyun');
				$data['realtime_image_url'] = $aliyun_config['pre_aliyun_img_url']. $aliyun_config['app_name'].'/'.$anchor_info['stream_id'].'.jpg';
			}
			$this->CI->db->where('id', (int)$anchor_id);
			$this->CI->db->update('user', $data);
			
			//判断用户是否在房间 写入直播间缓存
			$this->params['channel'] .= ':list';
			if(! $this->exists_key(":".$anchor_id)){
				$house_data['uid'] 					= $anchor_id;
				$house_data['nick'] 				= $anchor_info['nick'];
				$house_data['signature'] 			= $anchor_info['signature'];
				$house_data['head_image_url'] 		= $anchor_info['head_image_url'];
				$house_data['sex'] 					= $anchor_info['sex'];
				$house_data['image_url'] 			= $anchor_info['image_url'];
				$house_data['realtime_image_url'] 	= $data['realtime_image_url'];
				$house_data['verified_anchor'] 		= $anchor_info['verified_anchor'];
				$house_data['province'] 			= $anchor_info['province'];
				if(empty($anchor_info['house_password'])){
					$house_data['is_house_pass']  =  0;
				}else{
					$house_data['is_house_pass']  =  1;
				}
				$house_data['city'] 				= $anchor_info['city'];
				$house_data['title'] 				= $anchor_info['title'];
				$house_data['description'] 			= $anchor_info['description'];
				$house_data['orientation'] 			= $anchor_info['orientation'];
				$house_data['f_count']				= $anchor_info['f_count'];
				$house_data['up_count']				= $anchor_info['up_count'];
				$house_data['start_time']			= $anchor_info['start_time'];
				$house_data['cdn']					= $cdn;
				$house_data['history_count'] 		= $house_data['h_count'] = 0 + $anchor_info['h_count_base'];
				$house_data['type_name']			= '';
				$house_data['cate_id']			= $anchor_info['cate_id'];
				$house_data['live_up_count'] 		= 0;
				$house_data['type_id']				= $anchor_info['type_id'] = intval($anchor_info['type_id']);
				if($anchor_info['type_id'] > 0){
					$info = get_field_by_where('user_type', '*', 'id=' . $anchor_info['type_id']);
					if(!empty($info)){
						$house_data['type_name'] = $info['type_name'];
					}
				}
				
				//获取礼物总数
				$gift_info=get_field_by_where('gift_give_record','SUM(currency) as total',"anchor_id=".$anchor_id);
				$house_data['h_coupon'] = $house_data['live_h_coupon']=$house_data['gift_coupon'] = (int) $gift_info['total'];
				
				try {
					$return_list = $this->get_live_video_url($anchor_id, $cdn);
					$house_data['video_url'] = !empty($return_list['rtmp_video_url']) ? $return_list['rtmp_video_url'] : '';
				}catch (Exception $e) {
					$house_data['video_url'] = '';
				}
				$user_info = get_field_by_where('user', 'is_push', 'id=' . $anchor_id);
				if($user_info['is_push']==1){
					$this->push_live_list($house_data);
				}else{
					$this->save_house_info($anchor_id,$house_data);//如果is_push不为1 则只写入房间缓存 不写入直播列表缓存
				}
			}
			$this->save_anchor_room_gift($anchor_id, json_encode(array()));
			
			$this->CI->load->library('redis',array('model'=>'xmpp_redis','channel'=>'im'),'xmpp_redis');
			
			$result = array('result_code' => 1);
			$result = $this->CI->xmpp_redis->redis_class->return_room_member($anchor_info['uid'],$anchor_info,$result);
			
		}
		return $result;
	}
	//结束直播统一处理
	function end_live($anchor_id = 0,$post_data = array() ) {
		$result = array('result_code' => 1);
		try {
			$sql = "SELECT u.id AS anchor_id,u.id AS uid,aid,stream_id,start_time,image_url,cdn,live_up_count,h_count_base,disconnect_time FROM {$this->CI->db->dbprefix}user AS u WHERE 1=1 AND u.id = ".$anchor_id;
			
			$anchor_info = $this->CI->db->query($sql)->row_array();
			if(!empty($anchor_info['stream_id'])) {
				$result['result_data'] = $this->save_user_anchor_log($anchor_info,$post_data);
				$result['result_data']['share_url'] =  $this->CI->config->item('wap_url') . "/video/detail/0?u={$anchor_id}&t=".time();
		
			}else {
				$result = array('result_code' => 10033);
			}
		} catch (Exception $e) {
			$result = array('result_code' => 10033);
		}

		$data = array();
		$data['is_live']			= 0;
		$data['is_push']			= 0;
		$data['start_time']			= 0;
	//	$data['image_url']			= '';
		$data['disconnect_time']	= 0;
		$data['continue_time']		= 0;
		$data['end_time']			= 0;
		$data['live_up_count']		= 0;
		$this->CI->db->where('id', (int)$anchor_id);
		$this->CI->db->update('user', $data);
		if(stripos($this->params['channel'],':list')===false){
			$this->params['channel'] .= ':list';	
		}
		
		//主播完成了得到奖励
		$this->CI->load->library('integral',array('uid' => $anchor_id,'task_sign' => 'LIVEEX','extend'=>array('second'=>(int) $result['result_data']['second'])), 'WSZL');
		
		//关闭房间
		$this->delete_live_cache($anchor_id);
	//	$this->params['channel'] .= ':list';
		$this->del_live_h_coupon($anchor_id);
		$this->delete_live_house($anchor_id);//删除缓存
		$this->params['channel'] =str_replace('live:list','anchor',$this->params['channel']);
		$this->delete_anchor_beat($anchor_id);
		return $result;
		
	}
	
	//保存指定主播间的top10礼物统计
	function save_anchor_room_gift($anchor_id, $data){
		$key = $this->params['channel'].":gifttop:" . $anchor_id;
		$this->redis->set($key ,$data);//设置redis key
	}
	
	//获取指定主播间的top10礼物统计
	function get_anchor_room_gift($anchor_id){
		$key = $this->params['channel'].":gifttop:" . $anchor_id;
		return $this->redis->get($key);//设置redis key
	}
	//统一保存直播历史
	function save_user_anchor_log($anchor_info = array() ,$post_data = array() ) {
		//保存历史记录
		$user_anchor_log = array();
		$user_anchor_log['uid']			= $anchor_info['uid'];
		$user_anchor_log['stream_id']	= $anchor_info['stream_id'];
		$user_anchor_log['image_url']	= $anchor_info['image_url'];
		$user_anchor_log['cdn']			= $anchor_info['cdn'];
		$user_anchor_log['is_video']	= isset($post_data['is_video']) ? $post_data['is_video'] : 1; //是否成为视频
		$user_anchor_log['start_time']	= !empty($anchor_info['start_time']) ? $anchor_info['start_time'] : time();
		$user_anchor_log['end_time'] = time();
		$user_anchor_log['add_time'] = time();
		$user_anchor_log['second'] 	= $user_anchor_log['end_time'] - $user_anchor_log['start_time'];
		$user_anchor_log['aid'] 	= !empty($anchor_info['aid']) ? $anchor_info['aid'] : 0;
		
		//获取直播观看观众
		$viewer = 0;
		try{
			$this->CI->load->library('redis',array('model'=>'xmpp_redis','channel'=>'im'),'xmpp_redis');
			$viewer = count($this->CI->xmpp_redis->redis_class->get_room_history_by_members_temp($anchor_info['uid']));
			//删除当前历史
			
			$this->CI->xmpp_redis->redis_class->del_room_history_by_members_temp($anchor_info['uid']);
		}catch (Exception $e) {
			$viewer = 0;
		}
		
		$user_anchor_log['view']	= $viewer;
		
		$this->CI->db->insert('user_anchor_log', $user_anchor_log);
		
		//获取本次直播时长
		$duration = '';
		$seconds = $user_anchor_log['second'];
		if ($seconds > 3600) {
			$duration = intval($seconds/3600).'小时'.gmstrftime('%M分钟%S秒钟', $seconds);
		}else {
			$duration = gmstrftime('%H小时%M分钟%S秒钟', $seconds);
		}
		
		$this->CI->load->model('gift_give_records');
		$coupon = 0;
		$coupon = $this->CI->gift_give_records->get_anchor_field($where = array('anchor_id'=>$anchor_info['uid'],'add_time'=>$user_anchor_log['start_time']),'coupon');
		
		//获取本次直播获取的礼物数
		/*$coin = 0;
		$coin = $this->CI->gift_give_records->get_anchor_field($where = array('anchor_id'=>$anchor_info['uid'],'add_time'=>$user_anchor_log['start_time']),'coin');*/
		//直播任务
		
		$current_day=date('Ymd',time());
		$task_record = get_field_by_where("task_record", "id", "uid=". $anchor_info['uid'] ." AND sign='KSZB' AND add_time >= ". strtotime($current_day));
		if(!$task_record){
			//判断是否超过10分钟
			$this->CI->load->model('user_anchor_logs');
			$user_anchor_day_all_second = $this->CI->user_anchor_logs->get_field_by_where('SUM(second) AS second', "add_time >=".strtotime($current_day));
			if(!empty($user_anchor_day_all_second) && $user_anchor_day_all_second['second'] > (60 * 10) ){
				$this->CI->load->library('integral',array('uid'=>$anchor_info['uid'],'task_sign'=>'KSZB'), 'KSZB');
				$all_integral_info = $this->CI->KSZB->result;
			}
		}
		
		$result = array(
						'duration'	=> $duration,
						'viewer'	=> $viewer + $anchor_info['h_count_base'],//直播观看观众
						'likeer'	=> (int) $anchor_info['live_up_count'],//喜欢直播的观众
					    'second'		=> (int) $user_anchor_log['second'],
						'coupon'	=> $coupon,//直播接收的米券数
					);
		return $result;
	}
	//得到stream_id
	function get_stream_id($anchor_id = 0,$force=false) {
		$redis_anchor_key = $this->params['channel'].':anchor:'.$anchor_id;
		$redis_anchor_item = $this->get_anchor_cache( $redis_anchor_key );
		$return = $redis_anchor_item;
		//唯一stream_id
		if(empty($return['stream_id']) || $force) {
			$result = get_field_by_where("user", "stream_id,cdn", " id = ". $anchor_id);
			if($result){
				if($result['stream_id'] == ''  || $force){
					if ($result['cdn'] != 1) {
						if(strpos($result['stream_id'],'.') !== false){
							$return['stream_id'] = time().$anchor_id;
						}
					}else{
						if(strpos($result['stream_id'],'.') === false){
							$return['stream_id'] = $this->create_qiniu_stream();
						}
					}
					$this->CI->db->where('id', (int)$anchor_id);
					$this->CI->db->update('user', array('stream_id'=> $return['stream_id']));
				}else{
					$return['stream_id'] = $result['stream_id'];
				}
				$this->set_anchor_val_cache( $redis_anchor_key ,'stream_id', $return['stream_id']);
			}
		}
		return $return['stream_id'];
	}
	//得到七牛的stream
	function qiniu_stream($stream_id = '') {
		$CI =& get_instance();
		$CI->config->load('qiniu_config');
		$qiniu_config = $CI->config->item('THINK_SDK_QINIU');
		require_once ("third_party/pili/Pili.php");
		$this->cfg = \Pili\Config::getInstance();
		$this->cfg->API_HOST = 'pili-lte.qiniuapi.com';
		$this->credentials = new \Qiniu\Credentials($qiniu_config['APP_KEY'], $qiniu_config['APP_SECRET']); #=> Credentials Object
		$this->hub = new \Pili\Hub($this->credentials, $qiniu_config['HUB']); # => Hub Object
		$stream = $this->hub->getStream($stream_id); # => Stream Object
		return $stream;
	}
	//得到七牛的stream
	function create_qiniu_stream() {
		$CI =& get_instance();
		$CI->config->load('qiniu_config');
		$qiniu_config = $CI->config->item('THINK_SDK_QINIU');
		require_once ("third_party/pili/Pili.php");
		$this->cfg = \Pili\Config::getInstance();
		$this->cfg->API_HOST = 'pili-lte.qiniuapi.com';
		$this->credentials = new \Qiniu\Credentials($qiniu_config['APP_KEY'], $qiniu_config['APP_SECRET']); #=> Credentials Object
		$this->hub = new \Pili\Hub($this->credentials, $qiniu_config['HUB']); # => Hub Object
		
		$stream = $this->hub->createStream($title = '', $publishKey = '', $publishSecurity = 'static'); # => Stream 
		$stream_id = $stream->id;
		return $stream_id;
	}

	//仅仅从直播列表删除主播
    function delete_redis_live_list($house_id){
    	if(stripos($this->params['channel'],':list')===false){
			$this->params['channel'] .= ':list';	
		}
    	//删除所有主播的ZSet
		$this->redis->zDelete($this->params['channel'] . ":f_count", $house_id);
		$this->redis->zDelete($this->params['channel'] . ":start_time", $house_id);
		$this->redis->zDelete($this->params['channel'] . ":live_up_count", $house_id);
		$this->redis->zDelete($this->params['channel'] . ":h_count", $house_id);
		$this->redis->zDelete($this->params['channel'] . ":gift_coupon", $house_id);

		//删除认证主播的ZSet
		$this->redis->zDelete($this->params['channel'] . ":verified:f_count", $house_id);
		$this->redis->zDelete($this->params['channel'] . ":verified:start_time", $house_id);
		$this->redis->zDelete($this->params['channel'] . ":verified:live_up_count", $house_id);
		$this->redis->zDelete($this->params['channel'] . ":verified:h_count", $house_id);
		$this->redis->zDelete($this->params['channel'] . ":verified:gift_coupon", $house_id);

		//删除认未证主播的ZSet
		$this->redis->zDelete($this->params['channel'] . ":no_verified:f_count", $house_id);
		$this->redis->zDelete($this->params['channel'] . ":no_verified:start_time", $house_id);
		$this->redis->zDelete($this->params['channel'] . ":no_verified:live_up_count", $house_id);
		$this->redis->zDelete($this->params['channel'] . ":no_verified:h_count", $house_id);
		$this->redis->zDelete($this->params['channel'] . ":no_verified:gift_coupon", $house_id);
    }
    
    //仅仅保存主播到直播列表
    function save__redis_live_list($data){
    	if(!isset($data['uid'])||empty($data['uid']))  return false;
    	if(stripos($this->params['channel'],':list')===false){
			$this->params['channel'] .= ':list';	
		}
    	//设置所有主播的ZSet
		//粉丝排序
		$redis_live_key = $this->params['channel'].":f_count";
		$this->redis->zAdd($redis_live_key, $data['f_count'], $data['uid']);
		//开始时间排序
		$redis_live_key = $this->params['channel'].":start_time";
		$this->redis->zAdd($redis_live_key, $data['start_time'], $data['uid']);
		//本次直播赞排序
		$redis_live_key = $this->params['channel'].":live_up_count";
		$this->redis->zAdd($redis_live_key, $data['live_up_count'], $data['uid']);
		//本次直播观看人数排序
		$redis_live_key = $this->params['channel'].":h_count";
		$this->redis->zAdd($redis_live_key, $data['h_count'], $data['uid']);

		$redis_live_key = $this->params['channel'].":gift_coupon";
		$this->redis->zAdd($redis_live_key, $data['gift_coupon'], $data['uid']);

		if($data['verified_anchor'] == 1){//设置认证主播的ZSet
			//粉丝排序
			$redis_live_key = $this->params['channel'].":verified:f_count";
			$this->redis->zAdd($redis_live_key, $data['f_count'], $data['uid']);
			//开始时间排序
			$redis_live_key = $this->params['channel'].":verified:start_time";
			$this->redis->zAdd($redis_live_key, $data['start_time'], $data['uid']);
			//本次直播赞排序
			$redis_live_key = $this->params['channel'].":verified:live_up_count";
			$this->redis->zAdd($redis_live_key, $data['live_up_count'], $data['uid']);
			//本次直播观看人数排序
			$redis_live_key = $this->params['channel'].":verified:h_count";
			$this->redis->zAdd($redis_live_key, $data['h_count'], $data['uid']);

			$redis_live_key = $this->params['channel'].":verified:gift_coupon";
			$this->redis->zAdd($redis_live_key, $data['gift_coupon'], $data['uid']);
		}else{//设置未认证主播的ZSet
			//粉丝排序
			$redis_live_key = $this->params['channel'].":no_verified:f_count";
			$this->redis->zAdd($redis_live_key, $data['f_count'], $data['uid']);
			//开始时间排序
			$redis_live_key = $this->params['channel'].":no_verified:start_time";
			$this->redis->zAdd($redis_live_key, $data['start_time'], $data['uid']);
			//本次直播赞排序
			$redis_live_key = $this->params['channel'].":no_verified:live_up_count";
			$this->redis->zAdd($redis_live_key, $data['live_up_count'], $data['uid']);
			//本次直播观看人数排序
			$redis_live_key = $this->params['channel'].":no_verified:h_count";
			$this->redis->zAdd($redis_live_key, $data['h_count'], $data['uid']);

			$redis_live_key = $this->params['channel'].":no_verified:gift_coupon";
			$this->redis->zAdd($redis_live_key, $data['gift_coupon'], $data['uid']);
		}
    }
    
	//写入直播列表数据
	function push_live_list($data){
		$this->save__redis_live_list($data);

		$this->save_house_info($data['uid'],$data);
	}
    
    function save_house_info($house_id,$data){
    	if(stripos($this->params['channel'],':list')===false){
			$this->params['channel'] .= ':list';	
		}

    	$this->redis->hmset($this->params['channel'].":".$house_id, $data);	

    }
    
	//删除直播列表数据
	function delete_live_house($house_id){
		if(stripos($this->params['channel'],':list')===false){
			$this->params['channel'] .= ':list';	
		}
		$redis_live_key = $this->params['channel'].":".$house_id;
		$this->redis->del($redis_live_key);
		
		$this->delete_redis_live_list($house_id);
		
	}

	/**
	* 获取直播列表数据
	* REDIS KEY: dm.im:live:list...
	* 创建人: 	Zhou Hailong
	* 创建时间: 2016-05-03 14:11
	* @ string verified_status 是否筛选认证主播
	* @ string order_filed 排序字段
	* @ string order_by 升序or降序
	* @ int limit 分页参数
	* @ int offset 分页参数
	* @ array my_score 自定义score，如果此参数不为空则只返回包含在此参数中的直播间列表，目前用到该参数的接口(3.2.4获取关注用户的直播间列表)
	* 最后修改人：
	* 最后修改时间：
	*/
	function get_live_lists($verified_status = '', $order_filed = 'start_time', $order_by = 'DESC', $limit = 0, $offset = 10, $my_score = array(), $need_focus_user=false){
		$lists = $score = array();
		if($need_focus_user && empty($my_score)) return $lists;//获取主播关注裂变并且该主播的关注用户为空直接返回
			
		if($verified_status != ''){
			$key = $this->params['channel'] . ":" . $verified_status . ":" . $order_filed;
		}else{
			$key = $this->params['channel'] . ":" . $order_filed;
		}
		$star 	= !empty($limit)? $limit * $offset : $limit;
		$end	= !empty($offset) ? $offset * ($limit +1)  : $offset;
		$count = (int) $this->redis->zSize($key);
		if( !empty($count)) {
			if($order_by == 'DESC'){
				$score	= $this->redis->zRevRange($key, $star, ($end-1), FALSE);
			}else{
				$score	= $this->redis->zRange($key, $star, ($end-1), FALSE);
			}
			if($need_focus_user && count($my_score) > 0){
				$score = array_intersect($score, $my_score);
			}

			if(!empty($score)) {
				foreach($score as $key=>$val) {
					$live_info = $this->redis->hgetall($this->params['channel'] . ":" . $val);
					$lists[] = $live_info;
				}
			}
		}
		return $lists;
	}


	/**
	* 获取直播间数据
	* 创建人: 	Zhou Hailong
	* 创建时间: 2016-05-03 18:11
	* 最后修改人：
	* 最后修改时间：
	*/
	function get_live_info($house_id) {
		if(stripos($this->params['channel'],':list')===false){
			$this->params['channel'] .= ':list';	
		}
		if($this->exists_key(':'.$house_id)){
			$redis_live_key = $this->params['channel'].":".$house_id;
			$result = $this->redis->hgetall($redis_live_key);
		}else{
			$result = false;
		}
		return $result;
	}

	/**
	* 写入直播间本次直播收到的礼物总数（end_live时清除）
	* 创建人: 	Zhou Hailong
	* 创建时间: 2016-05-06 15:11
	* 最后修改人：
	* 最后修改时间：
	*/
	function push_live_h_coupon($house_id, $h_coupon){
		$this->redis->set($this->params['channel'].":h_coupon:".$house_id, $h_coupon);
	}

	/**
	* 获取直播间本次直播收到的礼物总数
	* 创建人: 	Zhou Hailong
	* 创建时间: 2016-05-06 15:11
	* 最后修改人：
	* 最后修改时间：
	*/
	function get_live_h_coupon($house_id){
		$h_coupon = $this->redis->get($this->params['channel'].":h_coupon:".$house_id);
		return $h_coupon;
	}

	function del_live_h_coupon($house_id){
		$redis_live_key = $this->params['channel'].":h_coupon:".$house_id;
		$this->redis->del($redis_live_key);
	}

	function get_all_live_video_url(){
		$data = array();
		$redis_anchor_key = $this->params['channel'].':anchor*';
		$result = $this->redis->keys($redis_anchor_key);
		foreach ($result as $key => $value) {
			$cache = $this->redis->hgetall($value);
			if(isset($cache['ws_rtmp_video_url']) && strstr($cache['ws_rtmp_video_url'], 'flv')){
				$cache['redis_key'] = $value;
				$this->redis->del($value);
				$data[] = $cache;
			}
		}
		print_r($data);
	}

	//异步心跳状态是否执行中
	function chk_cron_anchor_beat(){
		$key="anchor:cron_anchor_beat_status";
		if($this->redis->exists($key)){
			return true;
		}else{
			return false;
		}
	}
	
	function update_anchor_beat($anchor_id = ''){
		if(!empty($anchor_id)){
			$redis_live_key = "anchor:user_anchor:anchor_beat";
			$insert_pos=$this->redis->zAdd($redis_live_key,time(),$anchor_id);
			if($insert_pos===false){
				return false;
			}else{
				return true;
			}
		}
		return false;
	}
	//删除心跳
	function delete_anchor_beat($anchor_id = ''){
		if(!empty($anchor_id)){
			$redis_live_key = "anchor:user_anchor:anchor_beat";
			$this->redis->zRem($redis_live_key,$anchor_id);
		}
	}
	//检测心跳缓存是否存在
	function chk_anchor_beat($anchor_id = ''){
		$redis_live_key = "anchor:user_anchor:anchor_beat";
		$pos=$this->redis->zRank($redis_live_key,$anchor_id);
		if($pos===false){
			return false;
		}else{
			return true;
		}
	}
	
	//检测心跳不存在时更新直播开始时间
	function update_start_live_status($anchor_id = ''){
		if(!empty($anchor_id) && !$this->chk_anchor_beat($anchor_id)){
			$data = array();
			$data['is_live']			= 1;
			$data['is_push']			= 1;
			$data['disconnect_time'] 	= time();
			$this->CI->db->where('id', (int)$anchor_id);
			$this->CI->db->update('user', $data);
		}
	}
	
	//通过心跳是否结束直播
	function anchor_beat_end_live(){
		$redis_live_key = "anchor:user_anchor:anchor_beat";
		$beat_list = $this->redis->zRevRange($redis_live_key,0,-1, false);
		if($beat_list){
			foreach($beat_list as $key =>$anchor_id){
				if($anchor_id){
					$time=$this->redis->zScore($redis_live_key,$anchor_id);
					$time=(int)$time;
					echo (time() - $time).'_'.$anchor_id.'<br>';
					if((time() - $time) >300){
						$sql = "/*master*/ SELECT u.id AS anchor_id,u.is_live,u.is_push,disconnect_time FROM {$this->CI->db->dbprefix}user AS u WHERE 1=1 AND u.id = ".$anchor_id;
						$anchor_info = $this->CI->db->query($sql)->row_array();
						if($anchor_info){
							if($anchor_info['is_live'] &&  $anchor_info['is_push']){
								$this->params['channel']=str_replace('anchor','live',$this->params['channel']);
								// file_put_contents('uploads/logs/beat_'.time().'.txt', 'disconnect_time:'.$anchor_info['disconnect_time'] .'--end_time:'.time());
								$this->end_live($anchor_id);
								$this->params['channel'] =str_replace('live','anchor',$this->params['channel']);
								$this->delete_anchor_beat($anchor_id);
							}else{
								$this->delete_anchor_beat($anchor_id);
							}
						}else{
							$this->delete_anchor_beat($anchor_id);
						}
					}
				}
			}
		}
	}
	
	//最后一次回调记录
	function set_anchor_last_callback_time($anchor_id,$time){
		$key=$this->params['channel'].":anchor_last_callback_time".$anchor_id;
		$this->redis->set($key,$time);
	}
	//最后一次回调记录
	function get_anchor_last_callback_time($anchor_id){
		$key=$this->params['channel'].":anchor_last_callback_time".$anchor_id;
		return $this->redis->get($key);
	}
	
	//开始异步心跳状态
	function begin_cron_anchor_beat(){
		$key="anchor:cron_anchor_beat_status";
		$this->redis->setex($key,300,1);
	}
	
	//结束异步心跳状态
	function end_cron_anchor_beat(){
		$key="anchor:cron_anchor_beat_status";
		$this->redis->del($key);
	}


	//添加房间密码；
	public function add_anchor_house_password($anchor_id,$password) {
		$key = $this->params['channel'].":anchor_house_password:anchor_id:".$anchor_id;
		if(trim($password) == ""){
			if($this->redis->exists($key)){
				$this->redis->del($key);
			}
		}else{
			$this->redis->set($key,$password);
		}
	}

	//查询房间密码；
	public function check_anchor_house_password($anchor_id,$password) {
		$key = $this->params['channel'].":anchor_house_password:anchor_id:".$anchor_id;
		if(trim($password) == ""){
			if($this->redis->exists($key)){
				return true;
			}else{
				return false;
			}
		}else{
			$result = $this->redis->get($key);
			if($result == $password){
				return true;
			}else{
				return false;
			}
		}
	}

}